// login/pages/registe/registe.js
import { registe } from '../../../api/index'
import Toast from '@vant/weapp/toast/toast';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    phone: '',
    password: '',
    surePassword: '',
    name: '',
    code: '',
    agreen: false,
    errorMsg: {
      phone: '',
      password: '',
      surePassword: '',
      name: '',
      code:'',
      agreen:''
    }
  },
  //注册
  async registe() {
 
    let flag = true
    //是否有爆红提示
    for (let item in this.data.errorMsg) {
      if (this.data.errorMsg[item]) {
        flag = false
        return
      }
    }
    //同意协议
    if (!this.data.agreen) {
      flag = false
      Toast.fail('请勾选协议');
    }
    if (flag) {
      let result = await registe({
        phone: this.data.phone,
        password: this.data.password,
        name: this.data.name
      })
      if (result.data.code == 200) {
        Toast.success(result.data.msg);
        wx.navigateTo({
          url: '../login/login',
        })
      } else {
        Toast.fail(result.data.msg);
      }
    }
  },
  onLoad(options) {

  },
  //手机号输入框
  onPhone() {
    let reg_tel = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
    this.check(reg_tel, this.data.phone, 'errorMsg.phone', '手机号')
  },
  //密码
  onPassword() {
    let reg_pwd = /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{6,16}$/;
    this.check(reg_pwd, this.data.password, 'errorMsg.password', '密码')
  },
  //确认密码
  onSurePassword() {
    if (this.data.surePassword != this.data.password) {
      this.setData({
        'errorMsg.surePassword': '两次密码不一致'
      })
    } else {
      this.setData({
        'errorMsg.surePassword': ''
      })
    }
  },
  //名字
  onName() {
    let reg_name = /^[\u4e00-\u9fa5]{2,10}$/
    this.check(reg_name, this.data.name, 'errorMsg.name', '名字')
  },
  //验证码
  onCode(){
    let reg_code = /^\d{4}$/
    this.check(reg_code, this.data.code, 'errorMsg.code', '验证码')
  },
  // 表单校验函数
  check(reg, data, field, string) {
    if (data == '') {
      this.setData({
        [field]: string + '不能为空'
      });
    } else if (!reg.test(data)) {
      this.setData({
        [field]: '请输入正确的' + string
      });
    } else {
      this.setData({
        [field]: ''
      });
    }
  },
  onChange() {
    //勾选协议时
    this.setData({
      agreen: !this.data.agreen
    })
    console.log(this.data.agreen);
  },
  onClickLeft() {
    //左上角按钮
    wx.navigateTo({
      url: '../login/login',
    })
  }
})